<template>
  <div class="editname">
    <header>
      <van-nav-bar title="昵称" :border="false" class="title">
        <template #left>
          <van-icon name="arrow-left" size="15" @click="gotoback"></van-icon>
        </template>
        <template #right> <span @click="gotoindex">保存</span> </template>
      </van-nav-bar>
    </header>
    <div class="inputname">
      <van-cell-group inset>
        <van-field v-model="value" border clearable />
      </van-cell-group>
      <span class="label">用户昵称每月仅可修改一次</span>
    </div>
  </div>
</template>
<script>
import { useRouter } from "vue-router";
import { ref, onMounted } from "vue";
import { postEditApi, postEditChaXunApi } from "../../utils/loginapi";
import { Toast } from "vant";
export default {
  setup() {
    // 获取登录token
    const token = localStorage.getItem("token");
    // 输入框内容
    const value = ref("");
    onMounted(() => {
      postEditChaXunApi({ usertel: token }).then((res) => {
        value.value = res.data.username;
      });
    });

    // 路由跳转
    const $router = useRouter();
    const gotoback = () => {
      $router.replace("/edit/index");
    };
    // 保存事件，获取修改后端昵称，跳转
    const gotoindex = () => {
      if (value.value !== "") {
        postEditApi({ usertel: token, username: value.value }).then((res) => {
          if (res.status === 0) {
            $router.replace("/edit/index?username=" + value.value);
          } else {
            Toast("无法获取登录状态");
          }
        });
      } else {
        Toast("昵称不能为空");
      }
    };
    return {
      value,
      gotoback,
      gotoindex,
      onMounted,
    };
  },
};
</script>

<style lang="less">
:root {
  --van-nav-bar-icon-color: #000;
  --van-nav-bar-text-color: #000;
  --van-font-weight-bold: 900;
}
.editname {
  height: 100vh;
  background: #f5f5f5;
  .van-cell-group {
    margin: 10px 0;
    border-radius: 0;
  }
  .label {
    padding: 20px;
    font-size: 10px;
    font-family: PingFangSC;
    color: #b8b8b8;
    line-height: 16px;
  }
}
</style>
